package com.knife.tools;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ValidationCode extends HttpServlet
{
  private static final long serialVersionUID = 1L;

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0L);

    int width = 62; int height = 22;

    BufferedImage image = new BufferedImage(width, height, 
      1);

    Graphics g = image.createGraphics();

    g.setColor(getRandColor(230, 250));
    g.fillRect(0, 0, width, height);

    g.setFont(new Font("Times New Roman", 1, 17));

    int length = 4;
    Random rand = new Random();

    String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    int size = base.length();
    StringBuffer str = new StringBuffer();
    for (int i = 0; i < length; ++i) {
      int start = rand.nextInt(size);
      String tmpStr = base.substring(start, start + 1);

      str.append(tmpStr);

      g.setColor(getRandColor(10, 150));

      g.drawString(tmpStr, 13 * i + 6 + rand.nextInt(5), 14 + 
        rand.nextInt(6));
    }

    request.getSession().setAttribute("valiCode", str.toString());

    g.dispose();

    ImageIO.write(image, "JPEG", response.getOutputStream());
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    doGet(request, response);
  }

  Color getRandColor(int fc, int bc)
  {
    Random random = new Random();
    if (fc > 255)
      fc = 255;
    if (bc > 255)
      bc = 255;
    int r = fc + random.nextInt(bc - fc);
    int g = fc + random.nextInt(bc - fc);
    int b = fc + random.nextInt(bc - fc);
    return new Color(r, g, b);
  }
}